package com.symbio.ishenapi.patient.controller;


import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.symbio.ishenapi.common.controller.BaseController;
import com.symbio.ishenapi.patient.model.*;
import com.symbio.ishenapi.patient.model.base.BaseTmPatientMedicalRecords;
import com.symbio.ishenapi.patient.model.base.BaseTmPatientMedicalRecordsD;
import com.symbio.ishenapi.patient.util.Arith;
import io.jboot.Jboot;
import io.jboot.web.controller.annotation.RequestMapping;

import java.awt.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RequestMapping("/patient")
public class PatientController extends BaseController {

    /**
     *添加病例
     */
   /* public  void saveRecord(){
      //  System.out.print("1111111111111111111111111111111");
        TmPatientMedicalRecords tpr=(TmPatientMedicalRecords)getReqBodyObject(TmPatientMedicalRecords.class);
        Date date = new Date();
        tpr.setCreateTtime(date);
        if (tpr.getUserId() ==null || "".equals(tpr.getUserId())){
            renderJsonError(40003,"病例人员");
        }else if (tpr.getMedicalType() == null || "".equals(tpr.getMedicalType())){
            renderJsonError(40003,"问题类型");
        }else if (tpr.getMedicalType() == null || "".equals(tpr.getMedicalType())){
            renderJsonError(40003,"问题值");
        }
        else{
            tpr.save();
            renderJsonError(40003,"病例");
        }

    }*/

    /*
     * 病例附件
     *
     * */
   /* public  void saveRecords_d(){
        TmPatientMedicalRecordsD tmPatientMedicalRecordsD=(TmPatientMedicalRecordsD)getReqBodyObject(TmPatientMedicalRecordsD.class);
        Date date = new Date();
        tmPatientMedicalRecordsD.setCreateTime(date);
        if (tmPatientMedicalRecordsD.getMedicalValue() == null || "".equals(tmPatientMedicalRecordsD.getMedicalValue())){
            renderJsonError(40003,"问题描述");
        }else if (tmPatientMedicalRecordsD.getMedicalType() == null || "".equals(tmPatientMedicalRecordsD.getMedicalType())){
            renderJsonError(40003,"问题类型");
        }
        else {
            tmPatientMedicalRecordsD.save();
            renderJsonError(40001,"病例附件");
        }


    }*/


    /*
     * 查询病例
     * */
    public  void selectRecords() {

        TmPatientMedicalRecords tmPatientMedicalRecords=(TmPatientMedicalRecords)getReqBodyObject(TmPatientMedicalRecords.class);
        List<Record> medicalRecords = TmPatientMedicalRecords.dao.findMedicalRecords(tmPatientMedicalRecords.getId());
        if (medicalRecords ==null){
            renderJsonError(40003, "病例");
            return;
        }
        renderJsonRet(medicalRecords);
    }


    /*
     * 修改提交
     * */
   /* public void postUpdateRecords(){
        TmPatientMedicalRecords tpm=(TmPatientMedicalRecords)getReqBodyObject(TmPatientMedicalRecords.class);
        TmPatientMedicalRecords byId = TmPatientMedicalRecords.dao.findById(tpm.getId());
        if ( byId!=null){
            if (!StrKit.isBlank(tpm.getUserId())) byId.setUserId(tpm.getUserId());
            if (!StrKit.isBlank(tpm.getMedicalType())) byId.setMedicalType(tpm.getMedicalType());
            if (!StrKit.isBlank(tpm.getMedicalValue())) byId.setMedicalValue(tpm.getMedicalValue());
            byId.setCreateTtime(new Date());
            if (byId.update()){
                renderJsonRet(tpm.getId());
            }else {
                renderJsonError(40004);
            }
        }else{
            System.out.println("数据库中用户信息为空");
            renderJsonError(40003);
            return;
        }
    }*/

    /*
    * 患者基本信息查询  (已移到后台)
    * */
    /* public  void patientXx(){
         //TmPatientUser tm =(TmPatientUser)getReqBodyObject(TmPatientUser.class);
         String userId = getPara("userId");
         renderJsonRet(TmPatientUser.dao.finduser(new BigInteger(userId)));
     }*/

     /*患者基本信息添加*/
    /*public void patientSave() {(已移到后台)
        TmPatientUser tm = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
        Date date =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
        String time = sdf.format(date);
        tm.setCreateTtime(time);
        if (tm !=null)
            renderJsonRet(40001);
        else
            renderJsonError(40003,"患者基本");
    }*/

    /*
    * 患者基本信息修改  （已移到后台）
    * */
    /*public void patientUpdate(){
        TmPatientUser tm = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
        TmPatientUser tm1=TmPatientUser.dao.findById(tm.getId());
        if (tm1 !=null){
            if (!StrKit.isBlank(tm.getUserName())) tm1.setUserName(tm.getUserName());
            if (!StrKit.isBlank(tm.getUserMobilePhone())) tm1.setUserMobilePhone(tm.getUserMobilePhone());
            if (!StrKit.isBlank(tm.getUserEmail())) tm1.setUserEmail(tm.getUserEmail());
            if (!StrKit.isBlank(tm.getUserNickName())) tm1.setUserNickName(tm.getUserNickName());
            if (!StrKit.isBlank(tm.getUserSex())) tm1.setUserSex(tm.getUserSex());
            if (!StrKit.isBlank(tm.getUserCity())) tm1.setUserCity(tm.getUserCity());
            if (!StrKit.isBlank(tm.getUserIdCard())) tm1.setUserIdCard(tm.getUserIdCard());
            if (!StrKit.isBlank(tm.getUserBirthday())) tm1.setUserBirthday(tm.getUserBirthday());
            if (!StrKit.isBlank(tm.getUserDetailedAddress())) tm1.setUserDetailedAddress(tm.getUserDetailedAddress());
            if (!StrKit.isBlank(tm.getUserPostCode())) tm1.setUserPostCode(tm.getUserPostCode());
            tm1.getCreateTtime();
            if (tm1.update()){
                renderJsonRet(tm.getId());
            }else {
                renderJsonError(40004);
            }
        }else{
            System.out.println("数据库中用户信息为空");
            renderJsonError(40003);
            return;
        }
        }
*/
        /**
         *
         *
         * @Author GuoShunYou
         * @Description 查询是否为保险团用户
         * @date 上午 11:38   2018/11/1
         * @return void
         */
       /* public void  isnoinsurance(){   已移到后台
            TmPatientUser tm = (TmPatientUser) getReqBodyObject(TmPatientUser.class);
            TmPatientUser user=TmPatientUser.dao.isInsuranUser(tm.getId());
            if(user==null){
                renderJsonError(40016,"该用户");
                return;
            }
            if("1".equals(user.getIsNoinsurance())){
                renderJsonError(50001,"该用户是保险团用户");
            }else{
                renderJsonError(50003,"该用户不是保险团用户");
            }



        }*/


        /**
         *
         *
         * @Author GuoShunYou
         * @Description 通过userid、doctorid解绑患者医生关联
         * @date 下午 9:32   2018/11/8
         * @return void
         */
       /* public void delUserDoctor(){ （已移到后台）
            TmPatientDoctor tm = (TmPatientDoctor) getReqBodyObject(TmPatientDoctor.class);
            TmPatientDoctor tmdd=TmPatientDoctor.dao.delpatientdotor(tm);
            boolean b=tmdd.delete();
            if(b){
                renderJsonError(50001,"解绑关注");
            }else{
                renderJsonError(50001,"解绑关注");
            }


        }*/

       /**
        *
        *
        * @Author GuoShunYou
        * @Description 全肾管理  保存用户填写测试基本信息
        * @date 下午 2:53   2018/11/21
        * @return void
        */
       public void saveTmreportbasicMessage(){
           TmReportbasicmessage tm = (TmReportbasicmessage) getReqBodyObject(TmReportbasicmessage.class);
           Date date=new Date();
           SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           tm.setCreateDate(formatter.format(date));
           if(tm.save()){
               //查出报告模块
               TmReport tmre=TmReport.dao.getreport();
               String report=tmre.getReportContent();
               double weight=tm.getWeight();//体重
               BigDecimal newweitht=new BigDecimal(weight);
               double height=tm.getHeight();//身高
               BigDecimal newheight=new BigDecimal(height);

               String heightunit=tm.getHeightUnit();//身高单位
               if("cm".equals(heightunit)){
                   BigDecimal unitValue=new BigDecimal("100");
                   newheight=newheight.divide(unitValue);
               }
               //体重指数BMI
               System.out.println("newh:"+newheight+"  weight:"+weight+"  ret1:"+newheight.multiply(newheight));
               BigDecimal  ji=newheight.multiply(newheight);
               BigDecimal re=newweitht.divide(ji,2);

               report=report.replace("/BMI/",String.valueOf(re));
               //体重建议
               String bmisuggest=TmCkdGfr.dao.getBmiSuggest(re);
               report=report.replace("/BMIsuggest/",bmisuggest);

               double ser=tm.getSerumCreatinine();//血肌酐
               String serunit=tm.getSerumCreatinineUnit();//血肌酐单位
               int age=tm.getAge(); //年龄
               String sex=tm.getSex();//性别

               //获取GFR值
               if("umol/L".equals(serunit)){
                   ser= Arith.div(ser,88.41);
               }
               //double gfr=186*ser-1.154*age-0.203;
               //double gfr=Arith.mul(186,ser)-Arith.mul(1.154,age)-0.203;
               double gfr1=Arith.sub(Arith.mul(186,ser),Arith.mul(1.154,age));
               double gfr=Arith.sub(gfr1,0.203);
               // 1男   0女
               if ("0".equals(sex)){
                   //gfr=gfr*0.74;
                   gfr=Arith.mul(gfr,0.74);
               }

               System.out.println("GFR:"+gfr);

               //通过GFR获取所有对应建议
               TmCkdGfr ckd=TmCkdGfr.dao.getGFRSuggest(gfr);

               //GFR期数
               report=report.replace("/CKD/",ckd.getRank());

               report=report.replace("/GFR/",String.valueOf(gfr));

               //计算ACR
               double acr=0.0;
               if (tm.getUrineProteinQuantitation()!=null && !"".equals(tm.getUrineProteinQuantitation())){
                   acr=tm.getUrineProteinQuantitation();
               }else if(tm.getACR()!=null && !"".equals(tm.getACR())){
                   acr=tm.getACR();
               }else if(tm.getUrinalysis()!=null && !"".equals(tm.getUrinalysis())){
                   if ("阴性".equals(tm.getUrinalysis())){
                       acr=9;
                   }else if("±".equals(tm.getUrinalysis())){
                       acr=43;
                   }else if("H".equals(tm.getUrinalysis())){
                       acr=81;
                   }else if("2+".equals(tm.getUrinalysis())){
                       acr=315;
                   }else if("3+B及以上".equals(tm.getUrinalysis())){
                       acr=1073;
                   }
               }else {
                   //acr=tm.getUrinaryAlbumin()/tm.getUrineCreatinine();
                   //换算单位成g/L
                   if("mmol/L".equals(tm.getUrineCreatinineUnit())){
                       double acc=Arith.mul(tm.getUrineCreatinine(),0.1131196127);
                       acr=Arith.div(tm.getUrinaryAlbumin(),acc,3);

                   }else if("umol/L".equals(tm.getUrineCreatinineUnit())){
                       double acc=Arith.mul(tm.getUrineCreatinine(),0.0001131196);
                       acr=Arith.div(tm.getUrinaryAlbumin(),acc,3);


                   }else if("mg/L".equals(tm.getUrineCreatinineUnit())){
                       double acc=Arith.mul(tm.getUrineCreatinine(),0.001);
                       acr=Arith.div(tm.getUrinaryAlbumin(),acc,3);

                   }else{
                       acr=Arith.div(tm.getUrinaryAlbumin(),tm.getUrineCreatinine());
                   }
               }

               System.out.println("ACR:"+acr);
               //两年下降风险算数------待定
               //计算公式
               // 1 – 0.9676 ^ exp (-0.2245 × (age/10 – 7.036) + 0.3212 × (male – 0.5642) – 0.4553 × (eGFR/5 – 7.222) + 0.4469 × (logACR – 5.137))
              double a=Arith.sub(Arith.div(age,10),7.036);
              double aa=Arith.mul(-0.2245,a);
              double b=Arith.sub(Integer.valueOf(sex),0.5642);
              double bb=Arith.mul(b,0.3212);
              double c=Arith.div(gfr,5);
              double cc=Arith.sub(c,7.222);
              double ccc=Arith.mul(cc,0.4553);
              double d=Arith.sub(Math.log(acr),5.137);
              double dd=Arith.mul(d,0.4469);
              double ab=Arith.add(aa,bb);
              double ac=Arith.sub(ab,ccc);
              double result=Arith.add(ac,dd);
              System.out.println("result:"+result);
              double exp=Math.exp(result);

              System.out.println("exp:"+exp);
              double newexp=Arith.round(exp,0);
              System.out.println("newexp:"+newexp);
              double rets=Math.pow(-0.9676,newexp);
              double ret=Arith.sub(1,rets);
              System.out.println("rets++++"+rets);
               System.out.println("ret++++"+ret);
              String sik="";
              if(ret>=0 && ret<=0.1){
                  sik="低风险";
              }else if(ret>0.1 && ret<=0.2){
                  sik="中等风险";
              }else if(ret>0.2){
                  sik="高风险";
              }
              report=report.replace("/2年/",sik);

              //五年下降风险算法------待定
               // 1 – 0.8762 ^ exp (-0.2245 × (age/10 – 7.036) + 0.3212 × (male – 0.5642) – 0.4553 × (eGFR/5 – 7.222) + 0.4469 × (logACR – 5.137))
               double rets5=Math.pow(-0.8762,newexp);
               double ret5=Arith.sub(1,rets5);
               System.out.println("rets5:"+rets5);
               System.out.println("ret5:"+ret5);
               if(ret5>=0 && ret5<=0.05){
                   sik="低风险";
               }else if(ret5>0.05 && ret5<=0.15){
                   sik="中等风险";
               }else if(ret5>0.15){
                   sik="高风险";
               }
               report=report.replace("/5年/",sik);


               //骨及矿物质代谢异常
               report=report.replace("/代谢异常/",ckd.getMetabolism());
               //贫血
               report=report.replace("/贫血/",ckd.getAnemia());
               //实验室检查
               report=report.replace("/实验室检查/",ckd.getInspect());

               //健康管理建议
               String con=TmSugget.dao.getsuggestbyage(age,gfr);
               report=report.replace("/suggest/",con);
               //report=report.replace("\r\n","");

               //将报告保存
               TmReport tmReport=new TmReport();
               tmReport.setReportBasicId(new BigInteger(tm.getId().toString()));
               tmReport.setReportContent(report);
               tmReport.save();

               renderJsonRet(report);

           }else{
               renderJsonError(40002,"全肾测试答案");
           }


       }



}